<?php
namespace Home\Controller;

use Think\Controller;


class FendanController extends Controller {
    /*
   * 分单逻辑
   * */
    public function fendan_jiaoben(){
        //默认平均值为15；
        $average = getConfig('MIX_FENDAN_NUM');
        //记录日志
        if (!is_dir('./fendanLog/zd_fendan_log/')) mkdir('./fendanLog/zd_fendan_log/',0777,true);
        $file_name = "./fendanLog/zd_fendan_log/fendanLog".date('Y-m-d').".txt";
        $myfile = fopen($file_name, "a") or die("Unable to open file!");
        //获取可分配总人数未处理总人数

        //获取可分单人员ID
        $u  = M('admin_users',null)
            ->where(['admin_users.fendan_status'=>1,'r.role_id'=>['in','4,7'],'admin_users.ppid'=>2,'admin_users.user_status'=>1])
            ->join('left join admin_role_user r on admin_users.id = r.user_id ')
            ->getField('id',true);
        if($u) {
            $new_user = array_unique($u);
            $new_user_1 = implode(',', $new_user);
            var_dump($new_user);
            //获取可分配人员手里剩余未处理订单数量
            $users = M('consume_fendan_log', null)
                ->field('user_id,count(consume_id) as con_count')
                ->where(['status' => 2, 'user_id' => ['in', $new_user_1]])
                ->group('user_id')
                ->select();
            //数组处理 ---start-----
            //数据处理成
            //        Array
            //        (
            //            [7] => 2 （key为审核人ID，value为剩余未处理订单数量）
            //            [11] => 0
            //            [12] => 2
            //            [15] => 0
            //            [19] => 0
            //            [20] => 0
            //            [21] => 0
            //            [22] => 0
            //            [23] => 0
            //            [24] => 0
            //            [31] => 0
            //        )
            $consume_count = 0; //获取可分配人员未处理总订单数
            if($users){
                foreach ($users as $kk => $vv) {
                    $consume_count += $vv['con_count'];
                    $new_key[$vv['user_id']] = $vv['con_count'];
                }

            }
            foreach ($new_user as $key => $val) {
                $new_keys[$val] = 0;
            }

            foreach ($new_keys as $kk => $vv) {
                if($new_key){
                    if ($new_key[$kk] != 0) {
                        $new_keys[$kk] = $new_key[$kk];
                    }
                }else{
                    $new_keys[$kk] = 0;
                }

            }
            asort($new_keys);//获取可分配人员手里剩余未处理订单数量
            //---end-----

            //计算应该最大分配总单数
            $more_order_num =$average * count($new_keys);
            //计算本轮实际分配总订单数
            $sj_more_order_num = $more_order_num - $consume_count;
            //获取数据库未分配总订单集合
            $new_A = M('consume_history', null)
                ->where('type=4 and status = 24 and id not in (select consume_id from consume_fendan_log)')
                ->limit($sj_more_order_num)
                ->getField('id', true);
            if($new_A) {
                //获取数据库未分配总订单数量
                $no_consume_count = count($new_A);

                if ($no_consume_count != $sj_more_order_num) {
                    //计算平均值
                    $new_sj_consume_count = $consume_count + $no_consume_count;
                    $average = floor($new_sj_consume_count / count($new_keys));
                    if($average == 0){
                        $average = 1;
                    }
                    
                }

                foreach ($new_keys as $key => $val) {
                    if ($average > $val) {
                        $fendan_total = $average - $val;//每人应分配单数
                    } else {
                        $fendan_total = $average;//每人应分配单数
                    }

                    $new_data = array_slice($new_A, 0, $fendan_total);
                    if ($new_data) {
                        foreach ($new_A as $kkk => $vvv) {
                            if (in_array($vvv, $new_data)) {
                                unset($new_A[$kkk]);
                            }
                        }
                        $new_arr = [];
                        foreach ($new_data as $kk => $vv) {
                            $arr['consume_id'] = $vv;
                            $arr['user_id'] = $key;
                            $arr['add_time'] = time();
                            $arr['admin_id'] = 1;
                            $new_arr[] = $arr;
                            unset($vv);
                        }
                        $res = M('consume_fendan_log', null)->addAll($new_arr);
                        if($res){
                            $content = "【".date('Y-m-d H:i:s',time())."】 给审核人员ID【".$key."】分配订单数【".$fendan_total."】成功\n";
                        }else{
                            $content = "【".date('Y-m-d H:i:s',time())."】 给审核人员ID【".$key."】分配订单数【".$fendan_total."】失败；原因：". M('consume_fendan_log', null)->_sql()."\n";

                        }
                        fwrite($myfile, $content);
                    }
                }
            }else{
                $content =  "【".date('Y-m-d H:i:s',time())."】 没有可分配订单\n";
                fwrite($myfile, $content);
            }
        }else{
            $content =  "【".date('Y-m-d H:i:s',time())."】 没有可分配人员\n";
            fwrite($myfile, $content);
        }



    }
}